from django.conf import settings
from django.core.cache import cache
from rest_framework.generics import ListAPIView
from rest_framework.mixins import ListModelMixin, CreateModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet, ViewSetMixin

from utils.response import APIResponse
from . import models
from .serializer import SwimmingSerializer, SwimPeopleNumSerializer, SwimnumSerializer, BannerSerializer


class BannerView(ViewSetMixin, ListAPIView):
    queryset = models.Banner.objects.all().filter(is_delete=False).order_by('orders')[:settings.BANNER_COUNT]
    serializer_class = BannerSerializer

    def list(self, request, *args, **kwargs):
        banner_list = cache.get('banner_list_cache')
        if not banner_list:
            res = super().list(request, *args, **kwargs)
            banner_list = res.data
            cache.set('banner_list_cache', banner_list)
        return Response(data=banner_list)


class SwimHomeView(GenericViewSet, ListModelMixin):
    queryset = models.SwimmingsInfo.objects.all()
    serializer_class = SwimmingSerializer


class SwimNumAddView(GenericViewSet, ListModelMixin, CreateModelMixin):
    queryset = models.Swimnum.objects.all()
    serializer_class = SwimnumSerializer

    def create(self, request, *args, **kwargs):
        res = models.Swimnum.objects.first()
        models.Swimnum.objects.update(num=res.num + 1, total=res.total + 1)
        return APIResponse(msg='进馆+1')


class SwimNumCutView(GenericViewSet, CreateModelMixin):
    queryset = models.Swimnum.objects.all()
    serializer_class = SwimnumSerializer

    def create(self, request, *args, **kwargs):
        res = models.Swimnum.objects.first()
        if res.num > 0:
            models.Swimnum.objects.update(num=res.num - 1)
            return APIResponse(msg='进馆-1')
        return APIResponse(code=101, msg='人数已为零')


class SwimPeopleNumView(GenericViewSet, ListModelMixin):
    queryset = models.SwimPeopleNum.objects.order_by('-date')[:7]
    serializer_class = SwimPeopleNumSerializer
